package com.netposa.controller;

import com.netposa.utils.FTPUtils2;
import com.netposa.utils.FtpFileUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@CrossOrigin
@Controller
public class FtpFileUploadController {




    private static Map<String, Boolean> ipDirMap = new HashMap<>();

    private static Set<String> ipDirSet = new HashSet<>();


    @Value("${ftp.filepath}")
    private String rootDirath;

    //ftp处理文件上传
    @RequestMapping(value = "/ftpuploadimg", method = RequestMethod.POST)
    @ResponseBody
    public String uploadImg(@RequestParam("file") MultipartFile file,
                            HttpServletRequest request) throws IOException {

        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();


        Boolean flag = FtpFileUtil.uploadFile(fileName, inputStream);
        if (flag == true) {
            System.out.println("ftp上传成功！");
        }


        return "success";
    }


    //ftp处理文件上传
    @RequestMapping(value = "/upload2Ftp", method = RequestMethod.POST)
    @ResponseBody
    public boolean upload2Ftp(@RequestParam("file") MultipartFile file,
                              HttpServletRequest request) throws IOException {

        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String p1 = "192.168.43.122";
        boolean result = false;
        FTPClient ftpClient = null;
        try {
            ftpClient = FTPUtils2.getFTPClient();
            if (!ipDirSet.contains(p1)) {
                boolean b = FTPUtils2.makeDirectory(p1);
                if (b) {
                    ipDirSet.add(p1);
                }
            }
            ftpClient.changeWorkingDirectory(p1);
            result = FTPUtils2.uploadFile(fileName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ftpClient.changeWorkingDirectory("/");
        }
        return result;


    }

}

